#!/usr/bin/env bash

set -e

PREFIX="$(cd "$(dirname $(dirname "${BASH_SOURCE[0]}"))" && pwd)"
BLOOP="${PREFIX}/share/bloop/bloop.ogg"
STDOUT=

show_help() {
  cat<<USE
  USAGE:
    bloop [options]
  OPTIONS:
    --stdout|-s:      also echo to stdout
    --sound-file|-f:  sound to play rather than 'bloop'
  EXAMPLE:
    tail /var/log/error.log | bloop
USE
}

has?() {
    command -v "$1" > /dev/null 2>&1
}

zombie_reap() {
    wait
}

has? 'mplayer' || {
    printf "Mplayer not found :(\n"
    exit 1
}

trap zombie_reap EXIT

while [ -n "$1" ]; do
    case "$1" in
        --stdout|-s)
            STDOUT=1
            ;;
        --sound-file|-f)
            shift
            BLOOP="$1"
            if [ ! -f "$BLOOP" ]; then
                printf "'%s' not found! :(\n" "$BLOOP"
                exit 2
            fi
            ;;
        --help|-h)
            show_help
            exit 0
        ;;
    esac
    shift
done

while read x; do
    (( STDOUT == 1 )) && printf '%b\n' "$x"
    mplayer "$BLOOP" &>/dev/null &
    sleep 0.01
done
